import JSZip from 'jszip'
import { get } from 'lodash-es'

import { message } from '@/utils/antdHelper'
import onAppError from '@/utils/onAppError'
import { instance as axiosInstance, requestWithTry } from '@/utils/request'

import { Session } from './storage'

/**
 * 导出文件下载
 * @param {Object} param0
 * @param {Blob} param0.blob
 * @param {string} param0.fileName 文件名
 * @returns
 */
export const downloadBlobFile = ({ blob, fileName }) => {
  try {
    if ('msSaveOrOpenBlob' in navigator) {
      window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else if (window.URL) {
      let blobUrl = URL.createObjectURL(blob)
      const aElement = document.createElement('a')
      aElement.style.display = 'none'
      aElement.href = blobUrl
      aElement.download = fileName
      document.body.appendChild(aElement)
      aElement.click()
      setTimeout(() => {
        document.body.removeChild(aElement)
      }, 100)
    } else {
      message.warning('当前浏览器不支持文件导出下载，请使用Chrome浏览器')
      return
    }
  } catch (e) {
    console.error(e)
    onAppError(e)
  }
}

/**
 * 导出文件
 * @param {Object} param0
 * @param {string} param0.url 文件地址
 * @param {string} param0.method 请求方式
 * @param {Promise} param0.api 后端接口
 * @param {Object} param0.params 参数
 * @param {string} param0.fileName 导出文件名，文件格式从后端获取，后续文件名改从后端获取
 */
export const exportFile = async ({ url, method = 'get', api, params = {}, fileName }) => {
  try {
    let response
    if (api) {
      response = await requestWithTry(api, params)
    } else {
      response = await (method === 'get'
        ? axiosInstance.get(url, { params, responseType: 'blob', headers: { 'X-Auth-Token': Session.getToken() } })
        : axiosInstance.post(url, params, { responseType: 'blob', headers: { 'X-Auth-Token': Session.getToken() } }))
    }
    const contentDisposition = get(response, 'headers.content-disposition', '')
    const backFileName = contentDisposition
      .split(';')[1]
      .split(contentDisposition.includes('fileName') ? 'fileName=' : 'filename=')[1]
    const suffix = backFileName.replaceAll('"', '').match(/([^.]+)$/)[1]
    downloadBlobFile({
      blob: response.data,
      fileName: fileName ? `${fileName}.${suffix}` : decodeURIComponent(backFileName),
    })
  } catch (e) {
    onAppError(e)
  }
}

/**
 * 将多个文件导出成压缩包文件
 * @param {Object} param0
 * @param {Array<{name: string, url: string}>} param0.files
 * @param {String} param0.zipName
 */
export const exportZip = async ({ files, zipName }) => {
  const zip = new JSZip()
  const promises = files.map(async file => {
    // 处理：将接口请求回来的数据转成blob
    const response = await fetch(file.url)
    const blob = await response.blob()
    // 将所有 Blob 添加到 ZIP 文件中
    zip.file(file.name, blob)
  })
  // 一次性请求
  await Promise.all(promises)
  // 生成 ZIP 文件
  const content = await zip.generateAsync({ type: 'blob' })
  // 下载 ZIP 文件
  const link = document.createElement('a')
  link.href = URL.createObjectURL(content)
  link.download = `${zipName}.zip` // 设置压缩包name
  link.click()
  // saveAs(content, 'files.zip')
}
